﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ivy.SiteAdmin.Entity;
using Ivy.SiteAdmin.BusinessLogic;
using Ivy.SiteAdmin.IBusinessLogic;
using Ivy.UserRegistration.Entity;
using Ivy.UserRegistration.IBusinessLogic;
using Ivy.UserRegistration.BusinessLogic;

using Ivy.Common.Framework.GeneralUtility;
using DasIdeen.ViewEntity;

namespace DasIdeen.UserControls
{
	public partial class VideoContentControl : System.Web.UI.UserControl
	{
        #region  Variable & constant
        //All constants and local variable should be declared here
        ContentStatistics lContentStatistics = null;
        const string constVideoType = "VDO";
        const string constActivityCodeForUpdate = "UPD";
        const string constActivityCodeForCreate = "CRT";
        int lContentKey = -1;
        ScreenActionMode lActionMode = ScreenActionMode.UnKnown;
        #endregion  Variable & constant

        #region Constructor & Destructor
        //Generally not needed in UI layer
        #endregion Constructor & Destructor

        #region Properties
        //UI layer may have public custom properties. these are very handy for User Controls
        public ContentStatistics ContentStatisticsEntity
        {
            get
            {
                return lContentStatistics;
            }
            set
            {
                lContentStatistics = value;
                this.ContentKey = lContentStatistics.ContentKey;
            }

        }
        public Int32 ContentKey
        {
            get
            {
                return lContentKey;
            }
            set
            {
                lContentKey = value;
            }
        }
        public ScreenActionMode ActionMode
        {
            get
            {
                return lActionMode;
            }
            set
            {
                lActionMode = value;
            }
        }
        #endregion Properties

        #region Public Methods
        //UI layer may have public custom properties. these are very handy for User Controls
        public override void DataBind()
        {
            try
            {
                if (this.ContentStatisticsEntity != null)
                {
                    if (this.ContentKey != -1)
                    {
                        ContentSessionContext tempContentSessionContext;
                        if (Session["ContentSessionContext_" + this.ContentKey] != null)
                        {
                            tempContentSessionContext = (ContentSessionContext)Session["ContentSessionContext_" + this.ContentKey];
                        }
                        else
                        {
                            tempContentSessionContext = new ContentSessionContext();
                            tempContentSessionContext.ContectKey = this.ContentKey;
                        }
                        //For calculating total number of views
                        if (!tempContentSessionContext.IsAlreayViewed)
                        {
                            ContentMetaDataMaster lContentMetaDataMaster;
                            SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();

                            lContentMetaDataMaster = lSiteAdminContentManagementBus.GetContentSummryByContentKey(this.ContentKey);
                            lContentMetaDataMaster.ContentTotalViews = lContentMetaDataMaster.ContentTotalViews + 1;
                            lSiteAdminContentManagementBus.UpdateContentMetaData(lContentMetaDataMaster);
                            this.lblViews.Text = lContentMetaDataMaster.ContentTotalViews.ToString();
                            tempContentSessionContext.IsAlreayViewed = true;
                            Session["ContentSessionContext_" + this.ContentKey] = tempContentSessionContext;
                        }
                    }

                    TranslateEntityToUIControls(this.ContentStatisticsEntity);
                    InitializeScreenAfterDataBindForActionAndContentType(this.ContentStatisticsEntity);

                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }

        }

        public void DataBind(ContentStatistics pContentStatistics)
        {
            try
            {
                if (pContentStatistics != null)
                {
                    this.ContentStatisticsEntity = pContentStatistics;
                    this.DataBind();
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }
        #endregion Public Methods

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            try //All events in pages or user control should have try{} catch {} block.
            {
                //First check if the current logged in user is having proper role/authorization to access this page or not.
                if (IsUserAutherization())
                {
                    //TODO - Your code to display the initial layout/data etc.
                }
                else
                {
                    //TODO - Your code to redirect page to "NOT AUTHORIZED" page or any other page as required by the business logic.
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
                ContentMetaDataMaster lContentMetaDataMaster;
                ContentBinaryDataContent lContentBinaryDataContent = new ContentBinaryDataContent();
                if (this.ContentKey != -1)
                {
                    lContentMetaDataMaster = lSiteAdminContentManagementBus.GetContentSummryByContentKey(this.ContentKey);
                    lContentMetaDataMaster.Sys_ModifiedByID = GetCurrentUserKey();
                    TranslateUIControlsToEntity(lContentMetaDataMaster);
                    if (!lSiteAdminContentManagementBus.UpdateContentMetaData(lContentMetaDataMaster))
                    {
                        //Response.Redirect("~/Default.aspx");

                    }
                    else
                    {
                        //if (this.ContentStatisticsEntity.ContentTypeCode != constBlogType)
                        //{
                        //    lContentBinaryDataContent.Sys_CreatedByID = GetCurrentUserKey();
                        //    TranslateUIControlsToEntity(lContentBinaryDataContent, lContentMetaDataMaster);
                        //    lSiteAdminContentManagementBus.SaveContentBinaryData(lContentBinaryDataContent);
                        //}
                    }
                }
                else
                {
                    lContentMetaDataMaster = new ContentMetaDataMaster();
                    lContentMetaDataMaster.ContentTypeKey = this.ContentStatisticsEntity.ContentTypeKey;
                    lContentMetaDataMaster.Sys_CreatedByID = GetCurrentUserKey();
                    TranslateUIControlsToEntity(lContentMetaDataMaster);
                    if (!lSiteAdminContentManagementBus.AddContentMetaData(lContentMetaDataMaster))
                    {
                        //Response.Redirect("~/Default.aspx"); 
                    }
                    else
                    {
                        //if (this.ContentStatisticsEntity.ContentTypeCode != constBlogType)
                        //{
                        //    lContentBinaryDataContent.Sys_CreatedByID = GetCurrentUserKey();
                        //    TranslateUIControlsToEntity(lContentBinaryDataContent, lContentMetaDataMaster);
                        //    lSiteAdminContentManagementBus.SaveContentBinaryData(lContentBinaryDataContent);
                        //}
                    }
                }
                this.ContentStatisticsEntity = lSiteAdminContentManagementBus.GetSelectedContentMetaDataWithContentStatisticsByContentkey(lContentMetaDataMaster.ContentKey);
                this.ContentKey = this.ContentStatisticsEntity.ContentKey;
                //this.ActionMode = ScreenActionMode.Display;
                this.DataBind();
                
            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ContentSessionContext tempContentSessionContext;
                if (Session["ContentSessionContext_" + this.ContentKey] != null)
                {
                    tempContentSessionContext = (ContentSessionContext)Session["ContentSessionContext_" + this.ContentKey];
                }
                else
                {
                    tempContentSessionContext = new ContentSessionContext();
                    tempContentSessionContext.ContectKey = this.ContentKey;
                }
                if (!tempContentSessionContext.IsAlreadyVoted)
                {
                    ContentRating lContentRating = new ContentRating();
                    SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
                    TranslateUIControlsToEntity(lContentRating);
                    if (lSiteAdminContentManagementBus.SaveContentVotesRating(lContentRating))
                    {
                        RefreshData(this.lContentStatistics.ContentKey);
                        DataBind();
                    }
                    tempContentSessionContext.IsAlreadyVoted = true;
                    Session["ContentSessionContext_" + this.ContentKey] = tempContentSessionContext;
                }

            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }

        }

        protected void btnLike_Click(object sender, ImageClickEventArgs e)
        {
            try
            {

                ContentSessionContext tempContentSessionContext;
                if (Session["ContentSessionContext_" + this.ContentKey] != null)
                {
                    tempContentSessionContext = (ContentSessionContext)Session["ContentSessionContext_" + this.ContentKey];
                }
                else
                {
                    tempContentSessionContext = new ContentSessionContext();
                    tempContentSessionContext.ContectKey = this.ContentKey;
                }
                if (!tempContentSessionContext.IsAlreadyLiked)
                {
                    SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
                    ContentMetaDataMaster lContentMetaDataMaster;
                    lContentMetaDataMaster = lSiteAdminContentManagementBus.GetContentSummryByContentKey(this.ContentKey);
                    lContentMetaDataMaster.ContentTotalLikes = lContentMetaDataMaster.ContentTotalLikes + 1;
                    lSiteAdminContentManagementBus.UpdateContentMetaData(lContentMetaDataMaster);
                    this.lblLike.Text = lContentMetaDataMaster.ContentTotalLikes.ToString();
                    tempContentSessionContext.IsAlreadyLiked = true;
                    Session["ContentSessionContext_" + this.ContentKey] = tempContentSessionContext;
                }


            }
            catch (Exception ex)
            {
                ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            ContentMetaDataMaster lContentMetaDataMaster = new ContentMetaDataMaster();
            try
            {
                ContentBinaryDataContent lContentBinaryDataContent;
                SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
                lContentBinaryDataContent = lSiteAdminContentManagementBus.GetSelectedContentBinaryDataByKey(this.ContentKey);
                if (DownloadBinaryData(lContentBinaryDataContent))
                {


                    lContentMetaDataMaster = lSiteAdminContentManagementBus.GetContentSummryByContentKey(this.ContentKey);
                    lContentMetaDataMaster.ContentTotalDownloads = lContentMetaDataMaster.ContentTotalDownloads + 1;
                    lSiteAdminContentManagementBus.UpdateContentMetaData(lContentMetaDataMaster);

                    Response.Flush();
                    Response.End();
                }

            }
            catch (Exception ex)
            {
                //ExceptionUtility.ExceptionHandler(ex, Server.MapPath("~/"));
            }
            finally
            {
                this.lblTotalDownloads.Text = lContentMetaDataMaster.ContentTotalDownloads.ToString();
            }
        }

        #endregion Events

        #region Private Methods

        /// <summary>
        /// This method is to check if the current logged in user is having proper role/authorization to access this page or not.
        /// </summary>
        private bool IsUserAutherization()
        {
            bool _IsUserAutherization = false;
            //TODO - Your code to check authorization goes here.

            //for the time being let us allow the user to access this page.
            //but remove the below line once you have a proper logic.
            _IsUserAutherization = true;

            return _IsUserAutherization;
        }

        /// <summary>
        /// This method is to clear all UI controls which are data binded.
        /// </summary>
        private void ClearScreen()
        {
        }

        /// <summary>
        /// This method is to bind all the UI control like dropdown list or list box etc with the required initial data, 
        /// </summary>
        private void FillLoadLookUpData()
        {
        }

        /// <summary>
        /// This method is to load the UI with initial set of data based of the business logic.
        /// </summary>
        private void InitializeScreen()
        {
            ClearScreen();
            FillLoadLookUpData();
        }

        /// <summary>
        /// This method is to copy the entity properties that need to be displayed in the UI controls to the UI control.
        /// Example - [pUser] is an instance of an entity and is filled with specific USER data.
        /// and this user instance is to be displayed is an UI control text boxes.
        /// A sample code will look like the following:
        ///  this.txtFirstName.Text = pUser.UserFirstName; 
        ///  this.txtLastName.Text  = pUser.UserLastName; 
        ///  this.txtLoginId.Text   = pUser.UserLoginID;
        /// </summary>
        private void TranslateEntityToUIControls(ContentStatistics pContentStatistics)
        {
            this.lblContentName.Text = pContentStatistics.ContentName.ToString();
            this.Page.Title = pContentStatistics.ContentName;
            this.lblLike.Text = pContentStatistics.ContentTotalLikes.ToString();
            this.lblViews.Text = pContentStatistics.ContentTotalViews.ToString();
            this.lblRating.Text = pContentStatistics.AvrageRating.ToString();
            this.lblTotalVotes.Text = pContentStatistics.TotalVotes.ToString();
            this.lblTotalDownloads.Text = pContentStatistics.ContentTotalDownloads.ToString();
            this.lblDate.Text = pContentStatistics.Sys_DateOfCreation.ToShortDateString();
            this.lblAuthorName.Text = pContentStatistics.UserFirstName + " " + pContentStatistics.UserLastName.ToString();
            //Mrinmoy - Need to insert these labels in the UI
            //this.lblContentMetaTagKeyword.Text = pContentStatistics.ContentMetaTagKeyword;
            //this.lblContentMetaTagDescription.Text = pContentStatistics.ContentMetaTagDescription;
            this.lblContentDescription.Text = pContentStatistics.ContentHtmlData.ToString();
            if (pContentStatistics.ContentMetaTagDescription != string.Empty)
            {
                this.Page.MetaDescription = pContentStatistics.ContentMetaTagDescription;
            }
            if (pContentStatistics.ContentMetaTagKeyword != string.Empty)
            {
                this.Page.MetaKeywords = pContentStatistics.ContentMetaTagKeyword;
            }
        }

        /// <summary>
        /// This method is to copy the user entered data from the UI controls to the entity instance that will be used to sent the entity to any other layer.
        /// Example - [pUser] is an instance of an entity and is to be filled with specific USER data that has been captured in the screen.
        /// A sample code will look like the following:
        ///  pUser.UserFirstName = this.txtFirstName.Text; 
        ///  pUser.UserLastName  = this.txtLastName.Text; 
        ///  pUser.UserLoginID   = this.txtLoginId.Text; 
        /// </summary>
        private void TranslateUIControlsToEntity(ContentMetaDataMaster pContentMetaDataMaster)
        {
            pContentMetaDataMaster.ContentName = this.txtContentTitle.Text;
            pContentMetaDataMaster.ContentCode = "Video";
            pContentMetaDataMaster.ContentMetaTagKeyword = "Testing";
            pContentMetaDataMaster.ContentMetaTagDescription = "Testing";
            //if (this.txtContentMetaTagDescription.Text.Trim() != string.Empty)
            //{
            //    pContentMetaDataMaster.ContentMetaTagDescription = this.txtContentMetaTagDescription.Text;
            //}
            //else
            //{
            //    pContentMetaDataMaster.ContentMetaTagDescription = StringUtility.ConvertHtmlToString(this.ContentEditior.Content);
            //}
            //string EditorContent = Server.HtmlDecode(this.Editor.Text);
            pContentMetaDataMaster.ContentHtmlData = this.ContentEditior.Content;
        }

        private void InitializeScreenAfterDataBindForActionAndContentType(ContentStatistics pContentStatistics)
        {
            //if (pContentStatistics.ContentTypeCode != constBlogType)
            //{
            //    this.DivStatisticsDownloadBtn.Visible = true;
            //    this.DivDownloadBtn.Visible = true;
            //}
            //else
            //{
            //    this.DivStatisticsDownloadBtn.Visible = false;
            //    this.DivDownloadBtn.Visible = false;
            //}
            if (this.ContentKey != -1)
            {
                this.DivDisplayVideoContent.Visible = true;
                this.DivAddNewVideoContent.Visible = false;
            }
            else
            {
                this.DivDisplayVideoContent.Visible = false;
                this.DivAddNewVideoContent.Visible = true;
            }

            if (Session["UserContext"] != null)
            {
                UserContext tempUserSession = (UserContext)Session["UserContext"];
                if (tempUserSession.CurrentUser != null)
                {
                    UserRegistrationBus lUserRegistrationBus = new UserRegistrationBus();
                    string lActivityCode;
                    if (this.ActionMode != ScreenActionMode.New)
                    {
                        lActivityCode = constActivityCodeForUpdate;
                    }
                    else
                    {
                        lActivityCode = constActivityCodeForCreate;
                    }
                    if (lUserRegistrationBus.IsUserHavingContentUpdateAuthorization(tempUserSession.CurrentUser.UserKey, pContentStatistics.ContentKey, lActivityCode, pContentStatistics.ContentTypeCode))
                    {
                        if (this.ActionMode != ScreenActionMode.New)
                        {
                            //this.IsEditAuthorized = true;
                            //this.DivEditDelete.Visible = true;
                            if (this.ActionMode != ScreenActionMode.Edit)
                            {
                                // for display mode
                                //this.DivEditContent.Visible = false;
                                this.DivStatistics.Visible = true;
                                DisplayContentStatics(true);
                                //this.DivEditDelete.Visible = true;
                                //this.DivMainContentName.Visible = true;
                                //this.DivContentDescription.Visible = true;
                                this.DivDisplayVideoContent.Visible = true;
                            }
                        }
                        else
                        {
                            //For new content
                            this.DisplayContentStatics(false);
                            //this.DivMainContentName.Visible = false;
                            //this.DivEditDelete.Visible = false;
                            //this.DivContentDescription.Visible = false;
                            //this.DivEditContent.Visible = true;
                            this.DivAddNewVideoContent.Visible = true;
                            this.ContentStatisticsEntity.Sys_CreatedByID = tempUserSession.CurrentUser.UserKey.ToString();
                            //if (this.ContentStatisticsEntity.ContentTypeCode != constVideoType)
                            //{
                            //    this.DivUploadContents.Visible = true;
                            //    this.DivUploadContent.Visible = true;
                            //    this.DivUploadButton.Visible = false;
                            //    this.DivDownloadBtn.Visible = false;
                            //}
                            //else
                            //{
                            //    this.DivUploadContents.Visible = false;
                            //    this.DivUploadContent.Visible = false;
                            //    this.DivDownloadBtn.Visible = false;
                            //}
                        }
                    }
                }
            }

        }

        private void TranslateUIControlsToEntity(ContentRating pContentRating)
        {
            pContentRating.ContentRatingContentKey = this.ContentStatisticsEntity.ContentKey;
            pContentRating.ContentRatingValue = Convert.ToInt32(this.RadioButtonList1.SelectedItem.Value);
            User lUser = GetCurrentUser();
            if (lUser != null)
            {
                pContentRating.ContentRatingProviderUserKey = lUser.UserKey;
                pContentRating.ContentRatingProviderName = lUser.UserFirstName + " " + lUser.UserLastName;
                pContentRating.ContentRatingProviderEmail = lUser.UserPrimaryEmailID;
                pContentRating.Sys_CreatedByID = lUser.UserKey.ToString();
            }
            else
            {
                pContentRating.Sys_CreatedByID = "-1";
            }
        }

        private User GetCurrentUser()
        {
            User UserKey = null;
            if (Session["UserContext"] != null)
            {
                UserContext tempUserSession = (UserContext)Session["UserContext"];
                if (tempUserSession.CurrentUser != null)
                {
                    UserKey = tempUserSession.CurrentUser;
                }
            }
            return UserKey;
        }

        private string GetCurrentUserKey()
        {
            string UserKey = "-1";
            if (Session["UserContext"] != null)
            {
                UserContext tempUserSession = (UserContext)Session["UserContext"];
                if (tempUserSession.CurrentUser != null)
                {
                    UserKey = tempUserSession.CurrentUser.UserKey.ToString();
                }
            }
            return UserKey;
        }

        private void RefreshData(int pContentKey)
        {
            ContentStatistics lContentStatistics;
            SiteAdminContentManagementBus lSiteAdminContentManagementBus = new SiteAdminContentManagementBus();
            lContentStatistics = lSiteAdminContentManagementBus.GetSelectedContentMetaDataWithContentStatisticsByContentkey(pContentKey);
            this.ContentStatisticsEntity = lContentStatistics;
        }

        private bool DownloadBinaryData(ContentBinaryDataContent pContentBinaryDataContent)
        {
            bool IsOperationSuccessful = false;
            // Send the file to the browser
            Response.AddHeader("Content-type", pContentBinaryDataContent.ContentBinaryDataType);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + pContentBinaryDataContent.ContentBinaryDataFileName);
            Response.BinaryWrite(pContentBinaryDataContent.ContentBinaryData);
            IsOperationSuccessful = true;

            return IsOperationSuccessful;
        }

        private void DisplayContentStatics(bool pIsVisible)
        {
            if (this.ContentStatisticsEntity.ContentTypeCode != constVideoType)
            {
                this.DivLike.Visible = pIsVisible;
                this.DivViewer.Visible = pIsVisible;
                this.DivRating.Visible = pIsVisible;
                //this.DivComments.Visible = pIsVisible;
                this.DivStatisticsDownloadBtn.Visible = pIsVisible;
                this.Divdate.Visible = pIsVisible;
                this.DivAuthorName.Visible = pIsVisible;
            }
            else
            {
                this.DivLike.Visible = pIsVisible;
                this.DivViewer.Visible = pIsVisible;
                this.DivRating.Visible = pIsVisible;
                this.Divdate.Visible = pIsVisible;
                this.DivAuthorName.Visible = pIsVisible;
            }

        }

        #endregion Private Methods

        
	}
}